import { app, ipcMain, dialog } from 'electron';
import { bridgeKeys } from '/src/renderer/src/utils/dicts';
import { clearCache, getUpdateCacheDir } from './clearCache';
import { autoUpdater } from 'electron-updater';

export function useEvent(options = {}) {
  const { mainWindow } = options;
  return {
    on: {
      /*设置窗口最大化*/
      maximize() {
        ipcMain.on(bridgeKeys.maximize, () => {
          if (mainWindow.isMaximized()) {
            // 如果是最大化
            mainWindow.unmaximize(); // 取消窗口的最大化
            return;
          }
          mainWindow.maximize(); // 将窗口设置为最大化
        });
      },
      /*设置窗口最小化*/
      minimize() {
        ipcMain.on(bridgeKeys.minimize, () => {
          mainWindow.minimize(); // 将窗口设置为最小化
        });
      },
      /*退出应用*/
      quit() {
        ipcMain.on(bridgeKeys.quit, () => {
          app.quit();
        });
      },
      /*打开更改缓存目录的弹框*/
      changeCacheDirectory() {
        ipcMain.handle(bridgeKeys.changeCacheDirectory, async () => {
          // canceled boolean - 对话框是否被取消
          const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
            properties: ['openDirectory'],
            title: '请选择存放缓存的目录',
          });
          if (!canceled) {
            const selectedDirectory = filePaths[0];
            console.log(selectedDirectory, 'selectedDirectory');
            // TODO 待测试
            app.setPath('userData', selectedDirectory);
            return selectedDirectory;
          }
          return Promise.reject({ canceled, msg: '用户取消选择文件' });
        });
      },
      /*监听清除缓存*/
      clearCache() {
        ipcMain.handle(bridgeKeys.clearCache, () => clearCache());
      },
      /*开始下载应用*/
      startDownload(cb = () => {}) {
        ipcMain.on(bridgeKeys.startDownload, () => {
          cb();
        });
      },
      /*退出系统并安装*/
      quitAndInstall() {
        ipcMain.on(bridgeKeys.quitAndInstall, () => {
          autoUpdater.quitAndInstall(); // 退出并安装新应用
        });
      },
    },
    send: {
      /*监听下载进度条*/
      downloadProgress(info, currentVersion) {
        mainWindow.webContents.send(bridgeKeys.downloadProgress, { ...info, currentVersion });
      },
      /*发现新版本*/
      updateAvailable(info, currentVersion) {
        mainWindow.webContents.send(bridgeKeys.updateAvailable, { ...info, currentVersion });
      },
      /*已下载完成*/
      updateDownloaded() {
        mainWindow.webContents.send(bridgeKeys.updateDownloaded);
      },
      /*获取缓存目录*/
      getCachePath() {
        mainWindow.webContents.send(bridgeKeys.getCachePath, app.getPath('userData'));
      },
    },
  };
}
